//
//  YSWebViewCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/17.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSWebViewCtrl.h"
#import "CartView.h"
#import "YSVirtualProtocol.h"
#import "YSClubDataTool.h"
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "YSOrderViewCtrl.h"
#import "AnimUtils.h"
#import "YSHomeDataTool.h"
#import "YSMineDataTool.h"
#import "YSCommonReqTool.h"

@interface YSWebViewCtrl ()<UIWebViewDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate>

@property(nonatomic,strong) UIWebView *webview;
@property(nonatomic,copy) NSString *url;//页面访问地址
@property(nonatomic,copy) NSString *titleText;//页面标题
@property(nonatomic,strong)CartView *cartView;
@property(nonatomic,strong)UIImageView *animImage;
@end

@implementation YSWebViewCtrl
+(instancetype)initWithUrl:(NSString *)url title:(NSString *)title{
    YSWebViewCtrl *webView = [[self alloc] init];
    webView.url = url;
    webView.titleText = title;
    return webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:_titleText];
    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:cartView];
    _cartView = cartView;
    
    //重写返回键
    UIView *view = self.navigationItem.leftBarButtonItem.customView;
    if ([view isKindOfClass:[UIButton class]]) {
        [((UIButton *)view) removeTarget:self.navigationController action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [((UIButton *)view) addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    }
    
    //初始化webview
    _webview = [[UIWebView alloc]init];
    _webview.frame = CGRectMake(0, 0, SCREENW, SCREENH);
    [_webview setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_webview];
    _webview.opaque = NO;
    _webview.scalesPageToFit = YES;
    _webview.delegate = self;
    
    //加载数据
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
}

- (void)tapTitleRightItem:(UIBarButtonItem *)item{
    [Utils showCartCtrl:self];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *url = [self decodeFromPercentEscapeString:[request.URL absoluteString]];
    NSLog(@"url=%@",url);
    NSString *prefixStr  = @"yueshiopen://virtual?params=";
    if([url hasPrefix:prefixStr]){
        NSRange range =  [url rangeOfString:prefixStr];
        url =  [url substringFromIndex:range.length];
        YSVirtualProtocol *protocol = [YSVirtualProtocol objectWithKeyValues:url];
        if(protocol.linkType == YSVirtualProtocolAddCartProdMode){//加入购物篮
            [self requestProdDetail:protocol.entityId.integerValue type:NO];
            return NO;
        }else if(protocol.linkType == YSVirtualProtocolBuyProdMode){//立即购买
            [self requestProdDetail:protocol.entityId.integerValue type:YES];
            return NO;
        }else if (protocol.linkType == YSVirtualProtocolReceiVoucher){//领取代金券
            if(ISLOGIN){
                [YSMineDataTool receiveVoucherWithEntityId:protocol.entityId success:^(YSReceiveVoucher *result) {
                    if(result.isSucc){
                        ShowTips(@"领取成功");
                    }else{
                        ShowEnterTips(result.data);
                    }
                } failure:^(NSError *error) {
                    ShowTips(kRequestFailure);
                }];
            }else{
                [Utils showLoginCtrl:self];
            }
            return NO;
        }
    }
    if ([Utils dealUrlWithController:self url:url fromWebView:YES]) {
        NSString *suffix = @"login=1";
        if ([url hasSuffix:suffix]) {
            NSString *token = [DefaultsHelper stringForKey:kAppToken];
            url = [url stringByAppendingFormat:@"&token=%@", token];
            
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
            return NO;
        }
    }
    return YES;
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.title = theTitle;
    
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    _webview.scrollView.contentSize = actualSize;
    
    //根据webview加载的情况判断是否添加上返回的手势事件
    if (![self isCanBack]) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        }
    }else{
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        }
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(_cartView){
        NSInteger num = [DefaultsHelper integerForKey:kCartIndex];
        [_cartView setNum:num];
    }
    
    //这里是处理需要登录才能访问的webview页面，悦食暂时还没有
    NSString *url = [self.webview.request.URL absoluteString];
    NSString *prefixStr  = @"yueshiopen://virtual?params=";
    if([url hasPrefix:prefixStr]){
        NSRange range =  [url rangeOfString:prefixStr];
        url =  [url substringFromIndex:range.length];
        NSDictionary *params = [url JSONObject];
        YSVirtualProtocol *protocol = [YSVirtualProtocol objectWithKeyValues:params];
        if(protocol.isLogin){
            if(ISLOGIN){
                NSString *token =  [DefaultsHelper stringForKey:kAppToken];
                NSString *loadUrl = [NSString stringWithFormat:@"%@&token=%@",url,token];
                [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:loadUrl]]];
            }
        }
    }
}

//----------------以下为加入购物篮代码--------------//

/**
 *  请求商品信息
 *
 *  @param prodId 商品id
 *  @param type   是否是立即购买
 */
-(void)requestProdDetail:(NSInteger)prodId type:(BOOL)type{
    [YSClubDataTool getProductDetail:prodId isLogin:NO success:^(YSProductDetailRes *result) {
        if(result.isSucc){
            [self addToCart:result type:type];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

/**
 *  添加到购物篮
 *
 *  @param res  商品详情数据
 *  @param type 是否是立即购买
 */
-(void)addToCart:(YSProductDetailRes *)res type:(BOOL)type{
    if(ISLOGIN){
        [YSClubDataTool addCartWithParam:res.prodId prodCount:1 type:1 success:^(BaseResponse *result) {
            if(result.isSucc){
                if(type){//立即购买，跳转到结算中心,判断是否是体验券
                    AccountCenterProductType prodcutType = res.volume == 1?experienceProductType:ordinaryProductType;
                    
                    YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:nil selectProdIds:[NSString stringWithFormat:@"%ld",res.prodId] targetType:accountCenterFinishProductDetailType productType:prodcutType];
                    [ctrl setDelegate:self];
                    [self.navigationController pushViewController:ctrl animated:YES];
                }else{
                    [self startShopCartAnim:res];
                }
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }else{
        [Utils showLoginCtrl:self];
    }
}

-(void)startShopCartAnim:(YSProductDetailRes *)result{
    UIImage *image = [UIImage imageNamed:@"icon_add_cart"];
    _animImage = [[UIImageView alloc]initWithImage:image];
    _animImage.size = CGSizeMake(SCREENW/2, SCREENW/2);
    [_animImage.layer setCornerRadius:SCREENW/4];
    _animImage.layer.masksToBounds = YES;
    _animImage.center = _webview.center;
    [self.view addSubview:_animImage];
    [AnimUtils addToCartAnim:_animImage startView:_webview endView:_cartView delegate:self adverse:-1];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [_animImage removeFromSuperview];
    
    [self updateCartIndex];
}


-(void)updateCartIndex{
    //更新购物篮角标
    if(ISLOGIN){
        __weak typeof (self) weakSelf = self;
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
            [weakSelf.cartView setNum:count];
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

/**
 *  结算中心页面关闭回调
 *
 *  @param type
 *  @param status
 */
-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishProductDetailType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishProductDetailType];
    ctr.delegate = self;
    //进入状态页面
    [self.navigationController pushViewController:ctr  animated:YES];
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishProductDetailType == type){
        CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[YSOrderViewCtrl new]];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }
}

-(void)dealloc{
    self.webview.delegate = nil;
    [self.webview stopLoading];
}

-(void)back{
    if ([self isCanBack]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [_webview goBack];
    }
}

-(BOOL)isCanBack{
    return ![_webview canGoBack];
}

@end
